package cmd

import (
	"fmt"
	"github.com/xxjwxc/public/mylog"
	"os"

	"github.com/xxjwxc/gormt/data/view/gtools"

	"github.com/xxjwxc/gormt/data/config"

	"github.com/spf13/cobra"
	"github.com/xxjwxc/public/mycobra"
	"gopkg.in/go-playground/validator.v9"
)

var rootCmd = &cobra.Command{
	Use:   "main",
	Short: "gorm mysql reflect tools",
	Long:  `base on gorm tools for mysql database to golang struct`,
	Run: func(cmd *cobra.Command, args []string) {
		gtools.Execute()
		// Start doing things.开始做事情
	},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		os.Exit(1)
	}
}

func init() {
	fmt.Println(123)
	cobra.OnInitialize(initConfig)
	//指定配置文件
	rootCmd.Flags().StringP("config", "c", "gormt.yml", "配置文件")

	//命令行可指定表
	rootCmd.Flags().StringP("table_names", "b", "", "表名称")

}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	fmt.Println("initConfig")
	MergeMysqlDbInfo()
	validate := validator.New()
	err := validate.Struct(config.GetDbInfo())
	if err != nil {
		mylog.Info("Can't read cmd: using （-h, --help) to get more info")
		mylog.Error(err)
		os.Exit(1)
	} else {
		mylog.Info("using database info:")
		mylog.JSON(config.GetDbInfo())
	}
}

// MergeMysqlDbInfo merge parm
func MergeMysqlDbInfo() {

	//update tableNames. 更新tableNames
	tableNames := config.GetTableNames()
	mycobra.IfReplace(rootCmd, "table_names", &tableNames) // 如果设置了，更新
	config.SetTableNames(tableNames)

}
